package co.fitstart.mobile.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.product.Product;
import co.fitstart.entity.product.ProductType;
import co.fitstart.entity.product.Status;
import co.fitstart.mobile.entity.UserContext;
import co.fitstart.mobile.service.ProductService;
import co.fitstart.mobile.web.interceptor.MobileDetect;
import co.fitstart.mobile.web.interceptor.Router;

/**
 * Product related controller including 'product-list', 'product-view'
 * 
 * @author mohanlan
 */
@Controller
@RequestMapping("/products")
public class ProductController {

    private static Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;
    
    /**
     * list product by type
     * 
     * @param type
     * @param distributorId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @Router(targetUrl = "/products")
    @MobileDetect(autoLogin = false)
    @WechatJsConfig
    public ModelAndView list(@RequestParam(value = "type", defaultValue = "offline") String type,
                             @RequestParam(value = "distributorId", required = false) Long distributorId) {
        
        ModelAndView modelAndView = new ModelAndView("product/product-list");
        
        ProductType productType = ProductType.aliasOf(type);
        
        if(productType == null) {
            modelAndView.setViewName("redirect:/products");
            return modelAndView;
        }
        
        List<Product> products = productService.list(productType);
        
        if(distributorId != null) {
            modelAndView.addObject("distributorId", distributorId);
        }
        
        modelAndView.addObject("products", products);
        modelAndView.addObject("type", type);
        
        return modelAndView;
    
    }
    
    /**
     * Product product detail page, record source & from to update user behavior's read data
     * 
     * @param userContext
     * @param id
     * @param request
     * @param distributorId
     * @param source
     * @param from
     * @return
     */
    @RequestMapping(value = "/{productId}/view", method = RequestMethod.GET)
    @Router(targetUrl = "/products/detail")
    @MobileDetect(autoLogin = false)
    @WechatJsConfig
    public ModelAndView view(UserContext userContext,
                             @PathVariable("productId") Long id, 
                             HttpServletRequest request,
                             @RequestParam(value = "distributorId", required = false) Long distributorId,
                             @RequestParam(value = "source", required = false) String source,
                             @RequestParam(value = "from", required = false) String from) {
        
        ModelAndView modelAndView = new ModelAndView("product/product-detail");
        
        Product product = productService.get(Product.class, id);
        
        if(product == null || product.getStatus() != Status.ONLINE || product.isDisabled() || !product.isBuyable()) {
            modelAndView.setViewName("product/product-error");
            return modelAndView;
        }
        
        if(distributorId != null) {
            modelAndView.addObject("distributorId", distributorId);
        }
        
        // if current visitor environment is microMessenger, return to other pages
        if(userContext != null && userContext.isMicroMessenger()) {

            // only record when this product is viewed in wechat browser
            productService.readProduct(product, userContext.getOpenid(), StringUtils.isEmpty(from) ? source : from);
            
            modelAndView.setViewName("product/wechat-product-detail");
            
        }
        
        modelAndView.addObject("product", product);
        
        return modelAndView;
    }
    
    
    /**
     * Product product detail page, record source & from to update user behavior's read data
     * 
     * @param userContext
     * @param id
     * @param request
     * @param distributorId
     * @param source
     * @param from
     * @return
     */
    @RequestMapping(value = "/{productId}/view2", method = RequestMethod.GET)
    @Router(targetUrl = "/products/detail")
    @MobileDetect(autoLogin = false)
    @WechatJsConfig
    public ModelAndView view2(UserContext userContext,
                             @PathVariable("productId") Long id, 
                             HttpServletRequest request,
                             @RequestParam(value = "distributorId", required = false) Long distributorId,
                             @RequestParam(value = "source", required = false) String source,
                             @RequestParam(value = "from", required = false) String from) {
        
        ModelAndView modelAndView = new ModelAndView("product/product-detail");
        
        Product product = productService.get(Product.class, id);
        
        if(product == null || product.getStatus() != Status.ONLINE || product.isDisabled() || !product.isBuyable()) {
            modelAndView.setViewName("product/product-error");
            return modelAndView;
        }
        
        if(distributorId != null) {
            modelAndView.addObject("distributorId", distributorId);
        }
        
        // if current visitor environment is microMessenger, return to other pages
        if(userContext != null && userContext.isMicroMessenger()) {

            // only record when this product is viewed in wechat browser
            productService.readProduct(product, userContext.getOpenid(), StringUtils.isEmpty(from) ? source : from);
            
            modelAndView.setViewName("product/wechat-product-detail2");
            
        }
        
        modelAndView.addObject("product", product);
        
        return modelAndView;
    }
    
    /**
     * Share call back function, to record user behavior's share date
     * 
     * @param userContext
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/{productId}/wx-shared", method = RequestMethod.POST)
    public @ResponseBody String wxShare(UserContext userContext,
                                        @PathVariable("productId") Long id, 
                                        HttpServletRequest request) {
        
        Result result = new Result();
        
        try {
            
            logger.trace("#share() : into share controller with data id [" + id + "]");
            
            Product product = productService.load(Product.class, id);
            
            if(userContext != null && StringUtils.isNoneBlank(userContext.getOpenid())) {
                productService.shareProduct(product, userContext.getOpenid());
                result.success().message("分享回调成功");
            }else {
                result.success().message("当前使用环境不允许微信分享");
            }
            
        } catch (Exception e) {
            
            logger.error("#share() error:", e);
            result.fail().message("分享失败：" + e);
        }
        
        return JsonUtils.toJsonString(result);
    }
}
